package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;


import java.io.IOException;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(Integer[].class)    //映射的java类型
@MappedJdbcTypes(JdbcType.VARCHAR)   //映射的数据库类型
public class NewIntegerArrayTypeHandler extends BaseTypeHandler<Integer[]> {
    ObjectMapper objectMapper = new ObjectMapper();
    /***
     * @param preparedStatement
     * @param i    参数序号，是第几个参数
     * @param integers   为预编译的sql语句提供的参数 → 将第三个参数装换为数据库中能够接受的类型 → 在这里就是转化weistring
     * @param jdbcType
     * @throws SQLException
     */
    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        String s = objectMapper.writeValueAsString(integers);
        preparedStatement.setString(i, s);
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return transfer(result);
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String result = resultSet.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public Integer[] getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String result = callableStatement.getString(columnIndex);
        return transfer(result);
    }
    private Integer[] transfer(String result){
        if(result != null && "".equals(result)){

        }
        Integer[] integers = new Integer[0];
        try {
            integers = objectMapper.readValue(result, Integer[].class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
        return integers;
    }
}
